const express = require('express')
const router = express.Router()
const {
    Comment,
    User
} = require('../models')

// 添加评论(表单校验)
router.post('/home/addComments', async (req, res) => {
    // 接收数据
    const content = req.body.content
    const news_id = req.body.news_id
    const add_time = new Date()
    // 从jwt中解析用户的id
    const user_id = req.auth.user_id
    const nickname= req.auth.nickname
    const data = await Comment.create({
        content,
        newId: news_id,
        userId: user_id,
        add_time
    })
    data.dataValues.nickname = nickname
    return res.json({
        status: 200,
        msg: '添加成功',
        data
    })
})

// 评论列表
router.get('/home/comments', async (req, res) => {
    try {
        // 获取新闻id
        const news_id = parseInt(req.query.news_id)
        const data = await Comment.findAll({
            attributes: ['id', 'add_time', 'content'],
            where: {
                newId: news_id
            },
            order:[
               ['add_time','desc']
            ],
            include: [{
                model: User,
                attributes: ['nickname']
            }]
        })
        return res.cc(200, 'success', data)
    } catch (e) {
        return res.cc(400, e.message)
    }

})



module.exports = router